package clientView;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import object.Level;
import object.Role;
import object.Users;
import objectView.EmployeeInfo;
import utility.MD5;
import utility.MailUtil;
import utility.StringUtil;
import clientMain.Login;
import clientMain.Main;
import clientUtilGUI.KeyValue;
import clientUtilGUI.UtilityGUI;
import database.LevelDelegate;
import database.UserDelegate;

public class User_Create extends JScrollPane implements ActionListener{

	private JTable table;
	private JScrollPane scrollPane;
	private JPanel panelCreate;
	private JLabel lblUserName;
	private JTextField txtUserName;
	private JLabel lblAuthorization;
	private JLabel lblEmployeeId;
	private JTextField txtEmId;
	private JLabel lblRole;
	private JTextField txtRoleName;
	private JLabel lblRoleDescribe;
	private JTextField txtRoleDes;
	private JLabel lblLevel;
	private JComboBox cbbLvl;
	private JPanel panelBtn;
	private JButton btnCreate;
	private JButton btnCancel;
	private JPanel panelResult;
	private GridBagConstraints gbc_panelResult;	
	private JLabel lblNewAcc;
	private JLabel lblReturnPass;
	private JButton btnContinue;
	private JButton btnViewUser;
	
	private UserDelegate userDelegate = new UserDelegate();
	private String userName;
	private String passWord;
	private String userPassWord;
	private String emId;
	private String emEmail;
	private int level;
	private String roleName;
	private String roleDes;
	private Vector<String> vAuthorization;
	private String listRMP;
	
	
		
	public User_Create(){
		setViewportView(initComponet());
		setBorder(new EmptyBorder(0, 0, 0, 0));
	}
	
	private JPanel initComponet() {
		JPanel panel = new JPanel();
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0};
		gridBagLayout.rowWeights = new double[]{0.0, 1.0};
		panel.setLayout(gridBagLayout);
		
		JLabel lblHeader = new JLabel("Create New Account");
		lblHeader.setFont(UtilityGUI.fontHeader1);
		lblHeader.setForeground(UtilityGUI.colorHeader1);
		GridBagConstraints gbc_lblHeader = new GridBagConstraints();
		gbc_lblHeader.gridwidth = 2;
		gbc_lblHeader.insets = new Insets(10, 10, 15, 10);
		gbc_lblHeader.gridx = 0;
		gbc_lblHeader.gridy = 0;
		panel.add(lblHeader, gbc_lblHeader);
		
		panelCreate = new JPanel();
		GridBagConstraints gbc_panelCreate = new GridBagConstraints();
		gbc_panelCreate.insets = new Insets(0, 10, 10, 10);
		gbc_panelCreate.fill = GridBagConstraints.BOTH;
		gbc_panelCreate.gridx = 0;
		gbc_panelCreate.gridy = 1;
		panel.add(panelCreate, gbc_panelCreate);
		GridBagLayout gbl_panelCreate = new GridBagLayout();
		gbl_panelCreate.columnWidths = new int[]{0, 0, 0};
		gbl_panelCreate.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
		gbl_panelCreate.columnWeights = new double[]{0.0, 0.0, 1.0};
		gbl_panelCreate.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
		panelCreate.setLayout(gbl_panelCreate);
		
		lblUserName = new JLabel("Account :");
		lblUserName.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblUserName = new GridBagConstraints();
		gbc_lblUserName.insets = new Insets(0, 0, 5, 5);
		gbc_lblUserName.anchor = GridBagConstraints.WEST;
		gbc_lblUserName.gridx = 0;
		gbc_lblUserName.gridy = 0;
		panelCreate.add(lblUserName, gbc_lblUserName);
		
		txtUserName = new JTextField();
		GridBagConstraints gbc_txtUserName = new GridBagConstraints();
		gbc_txtUserName.fill = GridBagConstraints.BOTH;
		gbc_txtUserName.insets = new Insets(0, 0, 5, 5);
		gbc_txtUserName.gridx = 1;
		gbc_txtUserName.gridy = 0;
		panelCreate.add(txtUserName, gbc_txtUserName);
		txtUserName.setColumns(20);
		
		lblAuthorization = new JLabel("Authorization :");
		lblAuthorization.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblAuthorization = new GridBagConstraints();
		gbc_lblAuthorization.anchor = GridBagConstraints.EAST;
		gbc_lblAuthorization.insets = new Insets(0, 0, 5, 0);
		gbc_lblAuthorization.gridx = 2;
		gbc_lblAuthorization.gridy = 0;
		panelCreate.add(lblAuthorization, gbc_lblAuthorization);
		
		lblEmployeeId = new JLabel("Employee Id :");
		lblEmployeeId.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblEmployeeId = new GridBagConstraints();
		gbc_lblEmployeeId.anchor = GridBagConstraints.WEST;
		gbc_lblEmployeeId.insets = new Insets(3, 0, 5, 5);
		gbc_lblEmployeeId.gridx = 0;
		gbc_lblEmployeeId.gridy = 1;
		panelCreate.add(lblEmployeeId, gbc_lblEmployeeId);
		
		txtEmId = new JTextField();
		GridBagConstraints gbc_txtEmId = new GridBagConstraints();
		gbc_txtEmId.insets = new Insets(3, 0, 5, 5);
		gbc_txtEmId.fill = GridBagConstraints.BOTH;
		gbc_txtEmId.gridx = 1;
		gbc_txtEmId.gridy = 1;
		panelCreate.add(txtEmId, gbc_txtEmId);
		
		lblRole = new JLabel("Role :");
		lblRole.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblRole = new GridBagConstraints();
		gbc_lblRole.anchor = GridBagConstraints.WEST;
		gbc_lblRole.insets = new Insets(3, 0, 5, 5);
		gbc_lblRole.gridx = 0;
		gbc_lblRole.gridy = 2;
		panelCreate.add(lblRole, gbc_lblRole);
		
		txtRoleName = new JTextField();
		GridBagConstraints gbc_txtRole = new GridBagConstraints();
		gbc_txtRole.insets = new Insets(3, 0, 5, 5);
		gbc_txtRole.fill = GridBagConstraints.BOTH;
		gbc_txtRole.gridx = 1;
		gbc_txtRole.gridy = 2;
		panelCreate.add(txtRoleName, gbc_txtRole);
		
		lblRoleDescribe = new JLabel("Role Describe :");
		lblRoleDescribe.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblRoleDescribe = new GridBagConstraints();
		gbc_lblRoleDescribe.anchor = GridBagConstraints.WEST;
		gbc_lblRoleDescribe.insets = new Insets(3, 0, 5, 5);
		gbc_lblRoleDescribe.gridx = 0;
		gbc_lblRoleDescribe.gridy = 3;
		panelCreate.add(lblRoleDescribe, gbc_lblRoleDescribe);
		
		txtRoleDes = new JTextField();
		GridBagConstraints gbc_txtRoleDes = new GridBagConstraints();
		gbc_txtRoleDes.insets = new Insets(3, 0, 5, 5);
		gbc_txtRoleDes.fill = GridBagConstraints.BOTH;
		gbc_txtRoleDes.gridx = 1;
		gbc_txtRoleDes.gridy = 3;
		panelCreate.add(txtRoleDes, gbc_txtRoleDes);		
		
		if(Login.listAuthorization.get(0).getLvlValue()==1){
			lblLevel = new JLabel("Level :");
			lblLevel.setFont(UtilityGUI.fontHeader3);
			GridBagConstraints gbc_lblLevel = new GridBagConstraints();
			gbc_lblLevel.anchor = GridBagConstraints.WEST;
			gbc_lblLevel.insets = new Insets(3, 0, 5, 5);
			gbc_lblLevel.gridx = 0;
			gbc_lblLevel.gridy = 4;
			panelCreate.add(lblLevel, gbc_lblLevel);
			
			cbbLvl = new JComboBox();
			Vector<Level> listLvl;
			cbbLvl.setFont(UtilityGUI.fontComboBox);
			LevelDelegate lvlDelegate = new LevelDelegate();
			listLvl = lvlDelegate.getListLvl();
			cbbLvl.addItem("-- Select Level --");
			for(int i=0;i<listLvl.size();i++){
				String id = Integer.toString(listLvl.get(i).getLvlValue());
				String value = listLvl.get(i).getLvlDescribe();
				cbbLvl.addItem(new KeyValue(id, value));
			}
			GridBagConstraints gbc_comboBox = new GridBagConstraints();
			gbc_comboBox.insets = new Insets(3, 0, 5, 5);
			gbc_comboBox.fill = GridBagConstraints.BOTH;
			gbc_comboBox.gridx = 1;
			gbc_comboBox.gridy = 4;
			panelCreate.add(cbbLvl, gbc_comboBox);
		}
		
		panelBtn = new JPanel();
		GridBagConstraints gbc_panelBtn = new GridBagConstraints();
		gbc_panelBtn.gridwidth = 3;
		gbc_panelBtn.insets = new Insets(3, 0, 5, 0);
		gbc_panelBtn.fill = GridBagConstraints.BOTH;
		gbc_panelBtn.gridx = 0;
		gbc_panelBtn.gridy = 5;
		panelCreate.add(panelBtn, gbc_panelBtn);
		
		btnCreate = new JButton("Create");
		btnCreate.setMnemonic(KeyEvent.VK_ENTER);
		btnCreate.setFont(UtilityGUI.fontBtnForm);
		btnCreate.addActionListener(this);
		panelBtn.add(btnCreate);
		
		btnCancel = new JButton("Cancel");		
		btnCancel.setFont(UtilityGUI.fontBtnForm);
		btnCancel.addActionListener(this);
		panelBtn.add(btnCancel);
		
		panelResult = new JPanel();
		gbc_panelResult = new GridBagConstraints();
		gbc_panelResult.gridwidth = 3;
		gbc_panelResult.insets = new Insets(3, 0, 0, 0);
		gbc_panelResult.fill = GridBagConstraints.BOTH;
		gbc_panelResult.gridx = 0;
		gbc_panelResult.gridy = 6;
		panelCreate.add(panelResult, gbc_panelResult);
		
		table = UtilityGUI.getTblAuthorization(Login.listAuthorization.get(0).getUserName());
		scrollPane = new JScrollPane();
		scrollPane.setPreferredSize(new Dimension(500, 465));
		scrollPane.setViewportView(table);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.anchor = GridBagConstraints.NORTHWEST;
		gbc_scrollPane.insets = new Insets(0, 0, 10, 10);
		gbc_scrollPane.gridx = 1;
		gbc_scrollPane.gridy = 1;
		panel.add(scrollPane, gbc_scrollPane);
		
		return panel;
	}			
	
	private JPanel result(String emId){
		JPanel panel = new JPanel();
		GridBagLayout gbl_panelResult = new GridBagLayout();
		gbl_panelResult.columnWidths = new int[]{0, 0};
		gbl_panelResult.rowHeights = new int[]{0, 0, 0};
		gbl_panelResult.columnWeights = new double[]{1.0, 1.0};
		gbl_panelResult.rowWeights = new double[]{0.0, 0.0, 1.0};
		panel.setLayout(gbl_panelResult);
		
		lblNewAcc = new JLabel("Create New Account Succesfull!");
		lblNewAcc.setFont(UtilityGUI.fontHeader3);
		lblNewAcc.setForeground(UtilityGUI.colorHeader2);
		GridBagConstraints gbc_lblNewAcc = new GridBagConstraints();
		gbc_lblNewAcc.anchor = GridBagConstraints.WEST;
		gbc_lblNewAcc.insets = new Insets(0, 0, 5, 0);
		gbc_lblNewAcc.gridwidth = 2;
		gbc_lblNewAcc.gridx = 0;
		gbc_lblNewAcc.gridy = 0;
		panel.add(lblNewAcc, gbc_lblNewAcc);
		
		lblReturnPass = new JLabel("Account and Password sent Email of "+emId);
		lblReturnPass.setFont(UtilityGUI.fontHeader3);
		lblReturnPass.setForeground(UtilityGUI.colorLblForm);
		GridBagConstraints gbc_lblReturnPass = new GridBagConstraints();
		gbc_lblReturnPass.anchor = GridBagConstraints.WEST;
		gbc_lblReturnPass.gridwidth = 2;
		gbc_lblReturnPass.insets = new Insets(3, 0, 5, 0);
		gbc_lblReturnPass.gridx = 0;
		gbc_lblReturnPass.gridy = 1;
		panel.add(lblReturnPass, gbc_lblReturnPass);
		
		btnContinue = new JButton("Continue");
		btnContinue.setFont(UtilityGUI.fontBtnForm);
		btnContinue.addActionListener(this);
		GridBagConstraints gbc_btnContinue = new GridBagConstraints();
		gbc_btnContinue.anchor = GridBagConstraints.NORTHEAST;
		gbc_btnContinue.insets = new Insets(3, 0, 5, 5);
		gbc_btnContinue.gridx = 0;
		gbc_btnContinue.gridy = 2;
		panel.add(btnContinue, gbc_btnContinue);
		
		btnViewUser = new JButton("View User");
		btnViewUser.setFont(UtilityGUI.fontBtnForm);
		btnViewUser.addActionListener(this);
		GridBagConstraints gbc_btnViewUser = new GridBagConstraints();
		gbc_btnViewUser.anchor = GridBagConstraints.NORTHWEST;
		gbc_btnViewUser.insets = new Insets(3, 0, 5, 0);
		gbc_btnViewUser.gridx = 1;
		gbc_btnViewUser.gridy = 2;
		panel.add(btnViewUser, gbc_btnViewUser);
		
		return panel;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnCreate){
			
			//	VALID USER NAME
			if(!StringUtil.isValidUserName(txtUserName.getText())){
				JOptionPane.showMessageDialog(null, UtilityGUI.errorValidUserName, 
							UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
				txtUserName.requestFocusInWindow();
				return;
			}else{
				userName = txtUserName.getText();
				if(userDelegate.isExistsUserName(userName)){
					JOptionPane.showMessageDialog(null, UtilityGUI.errorExistsUserName, 
							UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
					txtUserName.requestFocusInWindow();
					return;
				}
			}
			
			//	VALID EM_ID			
			if(!StringUtil.isValidEmId(txtEmId.getText())){
				JOptionPane.showMessageDialog(null, UtilityGUI.errorValidEmIdEng, 
						UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
				txtEmId.requestFocusInWindow();
				return;
			}else{
				emId = txtEmId.getText();
				Vector<EmployeeInfo> list = Main.viewEm.searchEm(1, "Em_Id", emId);
				if(list == null || list.size() == 0){
					JOptionPane.showMessageDialog(null, UtilityGUI.errorExistsEmIdEng, 
							UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
					txtEmId.requestFocusInWindow();
					return;
				}else{
					boolean perm = false;
					for(int i=0; i<Login.listAuthorization.size();i++){
						if(Login.listAuthorization.get(i).getModuleDep() == list.get(0).getDepId()){
							perm = true;
							break;
						}
					}
					if(perm == false){
						JOptionPane.showMessageDialog(null, UtilityGUI.errorAuthEng, 
								UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
						txtEmId.requestFocusInWindow();
						return;
					}else {
						emId = list.get(0).getEmId();
						if(userDelegate.isExistsUserInfo(emId)){
							JOptionPane.showMessageDialog(null, emId+" had an account !",
									UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
							txtEmId.requestFocusInWindow();
							return;
						}else if(list.get(0).getEmEmail() == null || list.get(0).getEmEmail().isEmpty()){
							JOptionPane.showMessageDialog(null, emId+" doesn't have Email.Update, pls...",
									UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
							txtEmId.requestFocusInWindow();
							return;
						}else{
							emEmail = list.get(0).getEmEmail();
						}
					}
				}
			}
			
			//	VALID ROLE NAME
			if(!StringUtil.isValidRoleName(txtRoleName.getText())){
				JOptionPane.showMessageDialog(null, UtilityGUI.errorValidRoleName, 
						UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
				txtRoleName.requestFocusInWindow();
				return;
			}else{
				roleName = txtRoleName.getText();
				if(userDelegate.isExistsRoleName(roleName)){
					JOptionPane.showMessageDialog(null, UtilityGUI.errorExistsRoleName, 
							UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
					txtRoleName.requestFocusInWindow();
					return;
				}
			}
			
			//	VALID ROLE DESCRIBLE
			roleDes = txtRoleDes.getText();
			
			//	VALID AND GET LEVEL
			if(Login.listAuthorization.get(0).getLvlValue()==1){
				if(cbbLvl.getSelectedIndex() == 0){
					cbbLvl.requestFocusInWindow();
					return;
				}else{
					level = Integer.parseInt(((KeyValue)cbbLvl.getSelectedItem()).getKey());
				}
			}else{
				level = Login.listAuthorization.get(0).getLvlValue() + 1;
			}
			
			// LIST RMP	
			boolean flag = false;
			for(int i=0; i<Login.listAuthorization.size(); i++){
				if((Boolean) table.getValueAt(i, 4) == true){
					flag = true;
					break;
				}
			}
			if(flag == false){
				JOptionPane.showMessageDialog(null, UtilityGUI.errorPickAuthorization, 
						UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
				return;
			}
			vAuthorization = new Vector<String>();
			listRMP = "";
			for(int i=0; i<Login.listAuthorization.size(); i++){
				if((Boolean) table.getValueAt(i, 4) == true){
					String moduleId = ((KeyValue)table.getValueAt(i, 1)).getKey();
					String permId = ((KeyValue)table.getValueAt(i, 3)).getKey();
					vAuthorization.add(moduleId +"."+ permId);
				}
			}
			for(int i=0; i<vAuthorization.size(); i++){
				if(i == vAuthorization.size()-1){
					listRMP += vAuthorization.get(i);
				}else
					listRMP += vAuthorization.get(i)+",";
			}
			
			//	GET PASSWORD
			passWord = StringUtil.randomPwd(8);
			userPassWord = MD5.MD5Password(passWord);
			Users user = new Users();
			user.setUserName(userName);
			user.setUserPassword(userPassWord);
			user.setUserInfo(emId);
			user.setLvlValue(level);
			Role role = new Role();
			role.setRoleName(roleName);
			role.setRoleDescribe(roleDes);
			
			boolean flag1 = userDelegate.createAccount(user, role, listRMP);
			boolean isSendEmail = MailUtil.sendMailAuth(emEmail, userName, passWord);
			if(flag1 && isSendEmail){
				panelResult.setVisible(false);
				panelResult = result(emId);
				panelCreate.add(panelResult, gbc_panelResult);
			}else{
				JOptionPane.showMessageDialog(null, UtilityGUI.errorAction, 
							UtilityGUI.titleAlert, JOptionPane.INFORMATION_MESSAGE);
				return;
			}
			
		}else if(e.getSource() == btnCancel){
			Main.jTabbedPane.remove(this);
		}else if(e.getSource() == btnContinue){
			int index = Main.jTabbedPane.positionTab(UtilityGUI.tabUserCreate);
			Main.jTabbedPane.remove(this);
			Main.jTabbedPane.addTab(new User_Create(), UtilityGUI.tabUserCreate, index);
			Main.jTabbedPane.setSelectedIndex(index);
		}else if(e.getSource() == btnViewUser){
			Main.jTabbedPane.remove(this);
			int index = Main.jTabbedPane.positionTab(UtilityGUI.tabUserEdit);
			if(index == -1){
				Main.jTabbedPane.addTab(new User_Edit(), UtilityGUI.tabUserEdit);
				Main.jTabbedPane.setSelectedIndex(Main.jTabbedPane.getTabCount()-1);
			}else{
				Main.jTabbedPane.setSelectedIndex(index);
				return;
			}
		}
	}
}
